package com.test.jbpm;

import org.jbpm.api.TaskService;
import org.jbpm.api.cmd.Environment;
import org.jbpm.pvm.internal.cmd.AbstractCommand;
import org.jbpm.pvm.internal.model.ActivityImpl;
import org.jbpm.pvm.internal.model.ExecutionImpl;
import org.jbpm.pvm.internal.model.TransitionImpl;
import org.jbpm.pvm.internal.task.TaskImpl;


/**
 * “驳回”任务命令
 * 该驳回命令优点在于无需指定上一步骤的节点名称(previous activity)，只能用于那些只有一条返回路径的回退应用场景
 * @author ningjinlin
 *
 */
public class RegectTaskSingleBackWayCmd extends AbstractCommand<String>{

	private static final long serialVersionUID = 3407992369612709993L;

	private String taskId;
	
	public RegectTaskSingleBackWayCmd(String taskId) {
		super();
		this.taskId = taskId;
	}
	
	public String execute(Environment env) throws Exception {
		TaskService taskService = env.get(TaskService.class);
		TaskImpl currentTask = (TaskImpl)taskService.getTask(taskId);
		ExecutionImpl exec = currentTask.getProcessInstance();
		//获取当前任务的活动节点
		ActivityImpl currentActivity = exec.getActivity();
		//获取该活动节点的IncomingTransition
		TransitionImpl incomingTransition = (TransitionImpl)currentActivity.getIncomingTransitions().get(0);
		//获取IncomingTransition的源活动节点
		ActivityImpl sourceActivity = incomingTransition.getSource();
		
		TransitionImpl backTransition = currentActivity.createOutgoingTransition();
		
		//当前活动节点为新的回退Transition的源，而原来的“源”活动节点变成了目标活动节点
		backTransition.setSource(currentActivity);
		backTransition.setDestination(sourceActivity);
		backTransition.setName("regect "+incomingTransition.getName());
		taskService.completeTask(taskId,backTransition.getName());
		return sourceActivity.getName();
	}

}
